package com.ztgf.order.service.pay;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.dubbo.exception.ServiceException;
import com.ztgf.order.common.config.YmlConfig;
import com.ztgf.order.mapper.pay.PayOrderLogMapper;
import com.ztgf.order.models.bo.pay.PayOrderLogBO;
import com.ztgf.order.models.bo.pay.PayOrderSaveBO;
import com.ztgf.order.models.dto.OrderPaymentTypeDTO;
import com.ztgf.order.models.dto.pay.PayOrderLogDTO;
import com.ztgf.order.models.service.IOrderPaymentTypeService;
import com.ztgf.order.models.service.pay.IPayOrderLogService;
import com.ztgf.order.models.vo.pay.*;
import com.ztgf.pay.models.bo.PayOrderMotherSaveBO;
import com.ztgf.pay.models.bo.PayUserMoneySaveBO;
import com.ztgf.pay.models.bo.PayUserRechargeSaveBO;
import com.ztgf.pay.models.dto.PayOrderDTO;
import com.ztgf.pay.models.dto.PayOrderMotherDTO;
import com.ztgf.pay.models.dto.PayUserRechargeDTO;
import com.ztgf.pay.models.service.IPayOrderService;
import com.ztgf.pay.models.service.IPayUserRechargeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 支付日志表控制器
 *
 * @author mxli
 * @Date 2021-06-03 16:12:28
 */
@DubboService
@Slf4j
@Lazy
public class PayOrderLogServiceImpl extends ServiceImpl<PayOrderLogMapper, PayOrderLogDTO> implements IPayOrderLogService{

    @Resource
    private YmlConfig ymlConfig;
    @DubboReference
    private IPayOrderService payOrderService;
    @DubboReference
    private IPayUserRechargeService payUserRechargeService;
    @Autowired
    private IPayNotifyService payNotifyService;
    @Autowired
    private IOrderPaymentTypeService orderPaymentTypeService;


    public void savePayParams(List<PayOrderLogDTO> logDTOList, List<PayOrderDTO> orderDTOList
            , Long orderId, Long orderPeriodsId, Integer periods, Long recvShopId, Long commodityBargainId, Long oldPayOrderLogId
            , Long userId, String userName, Long payShopId, Integer payType, Integer moneyStatus, Integer businessType
            , Integer orderType, String bankId, String bankName, BigDecimal money, String moneyUsage, String commodityMsg
            , String trsFlag){
        savePayParams(logDTOList, orderDTOList
                , orderId, orderPeriodsId, periods, recvShopId, commodityBargainId, oldPayOrderLogId
                , userId, userName, payShopId, payType, moneyStatus, businessType
                , orderType, bankId, bankName, money, moneyUsage, commodityMsg
                , trsFlag, null);
    }

    /**
     * 重载的方法
     * @auther liyang
     * @param logDTOList
     * @param orderDTOList
     * @param orderId
     * @param orderPeriodsId
     * @param periods
     * @param recvShopId
     * @param commodityBargainId
     * @param oldPayOrderLogId
     * @param userId
     * @param userName
     * @param payShopId
     * @param payType
     * @param moneyStatus
     * @param businessType 金额类型：0订单金额，1佣金、2缴纳保证金、3年费、4采购申请平台砍价、5砍价手续费、6重复支付，7售后退款、8解冻保证金、9扣除保证金、10取消订单退款、11取消砍价服务费退款、12售后服务费退款、13签收解冻金额\n、14解冻砍价手续费、15缴纳物流保证金，16解冻物流保证金、17扣除物流保证金、18支付物流账单、19佣金退款
     * @param orderType
     * @param bankId
     * @param bankName
     * @param money
     * @param moneyUsage
     * @param commodityMsg
     * @param trsFlag
     * @param notes
     */
    public void savePayParams(List<PayOrderLogDTO> logDTOList, List<PayOrderDTO> orderDTOList
            , Long orderId, Long orderPeriodsId, Integer periods, Long recvShopId,Long commodityBargainId, Long oldPayOrderLogId
            ,Long userId, String userName, Long payShopId, Integer payType, Integer moneyStatus, Integer businessType
            ,Integer orderType, String bankId, String bankName, BigDecimal money, String moneyUsage, String commodityMsg
            ,String trsFlag,String notes){
        if(payType == 0 && (commodityBargainId != null || orderId != null || orderPeriodsId != null)){
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("pay_type", 0);
            wrapper.eq("type", businessType);
            if(commodityBargainId != null){
                wrapper.eq("commodity_bargain_id", commodityBargainId);
            }
            if(orderId != null){
                wrapper.eq("order_id", orderId);
            }
            if(orderPeriodsId != null){
                wrapper.eq("order_periods_id", orderPeriodsId);
            }
            Object[] status = {0, 1};
            wrapper.in("status", status);
            PayOrderLogDTO logDTO = this.selectOne(wrapper);
            if(logDTO != null){
                throw new ServiceException(CodeEnum.FAIL_ORDER_300018);
            }
        }

        PayOrderLogDTO logDTO = newLogDTO(orderId, orderPeriodsId, periods, recvShopId,commodityBargainId, oldPayOrderLogId
                , userId, userName, payShopId, payType, moneyStatus, businessType
                , orderType, bankId, bankName, money);
        logDTO.setNotes (notes);
        logDTOList.add(logDTO);
        //{bankId:银行id,bankName:银行名称," +
        //            "money:付款金额,businessOrderNo:业务订单号,businessOrderWaterNo:业务订单流水号,receiveUserId:收款方id," +
        //            "moneyUsage:资金用途,commodityMsg:商品信息," +
        //            "businessType:金额类型：金额类型：0订单金额，1佣金、2缴纳保证金、3年费、4采购申请平台砍价、5砍价手续费、6重复支付，7预售退款、8解冻保证金、9扣除保证金}
        PayOrderDTO orderDTO = new PayOrderDTO();
        orderDTO.setBankId(bankId);
        orderDTO.setBankName(bankName);
        orderDTO.setMoney(money);
        if(orderId != null){
            orderDTO.setBusinessOrderNo(orderId.toString());
        } else if(commodityBargainId != null){
            orderDTO.setBusinessOrderNo(commodityBargainId.toString());
        } else {
            orderDTO.setBusinessOrderNo(payShopId.toString());
        }

        orderDTO.setBusinessOrderWaterNo(logDTO.getId().toString());
        orderDTO.setReceiveUserId(recvShopId);
        orderDTO.setMoneyUsage(moneyUsage);
        orderDTO.setCommodityMsg(commodityMsg);
        orderDTO.setBusinessType(businessType);
        // 业务标示:
        // 余额支付：A00 普通订单支付,B00 收款方收款成功后，再冻结资金, B01 付款方解冻资金后，再支付给收款方；
        // 网银支付： A00 入金并支付 B00 收款方收款成功后，再 冻结资金
        orderDTO.setTrsFlag(trsFlag);
        orderDTOList.add(orderDTO);
    }

    /**
     * 添加日志
     * @param orderId 订单id
     * @param orderPeriodsId 订单分期支付id
     * @param periods 期数
     * @param recvShopId 卖家id
     * @param commodityBargainId  店铺报价表id
     * @param oldPayOrderLogId  重复支付原支付订单流水号
     * @param userId 用户id
     * @param userName 用户名称
     * @param payShopId 买家id
     * @param payType  支付类型：0余额，1网银，2票据
     * @param moneyStatus 金额状态：0未冻结，1冻结
     * @param businessType //金额类型：0订单金额，1佣金、2缴纳保证金、3年费、4采购申请平台砍价、5砍价手续费、6重复支付，7售后退款、8解冻保证金、9扣除保证金、10取消订单退款、11取消砍价服务费退款、12售后服务费退款、13签收解冻金额、14解冻砍价手续费、15缴纳物流保证金，16解冻物流保证金、17扣除物流保证金、18支付物流账单
     * @param orderType //支付类型：0支付，1退款、2冻结、3解冻
     * @param bankId 银行id
     * @param bankName 银行名称
     * @param money 金额
     * @param notes  备注
     * @param billName 票据支付名称
     * @param billUrl 票据支付图片
     * @return
     */
    public PayOrderLogDTO newLogDTO(Long orderId, Long orderPeriodsId, Integer periods, Long recvShopId,Long commodityBargainId, Long oldPayOrderLogId
            ,Long userId, String userName, Long payShopId, Integer payType, Integer moneyStatus, Integer businessType
            ,Integer orderType, String bankId, String bankName, BigDecimal money, String notes, String billName, String billUrl){
        PayOrderLogDTO logDTO = new PayOrderLogDTO();
        Long logId = ymlConfig.getPkId();
        logDTO.setId(logId);
        logDTO.setCreateUserId(userId);
        logDTO.setCreateUserName(userName);
        logDTO.setOrderId(orderId);
        logDTO.setOrderPeriodsId(orderPeriodsId);
        logDTO.setCommodityBargainId(commodityBargainId);
        logDTO.setOldPayOrderLogId(oldPayOrderLogId);
        logDTO.setPeriods(periods);
        logDTO.setPayShopId(payShopId);
        logDTO.setRecvShopId(recvShopId);
        logDTO.setMoney(money);
        logDTO.setPayType(payType);
        logDTO.setMoneyStatus(moneyStatus);//金额状态：0未冻结，1冻结
        logDTO.setType(businessType);//金额类型：0订单金额，1佣金、2缴纳保证金、3年费、4采购申请平台砍价、5砍价手续费、6重复支付，7售后退款、8解冻保证金、9扣除保证金、10取消订单退款、11取消砍价服务费退款、12售后服务费退款、13签收解冻金额、14解冻砍价手续费、15缴纳物流保证金，16解冻物流保证金、17扣除物流保证金、18支付物流账单
        logDTO.setPayOrderType(orderType);//支付类型：0支付，1退款、2冻结、3解冻
        logDTO.setBankId(bankId);
        logDTO.setBankName(bankName);
        logDTO.setBillName(billName);
        logDTO.setBillUrl(billUrl);
        logDTO.setNotes(notes);
        return logDTO;
    }

    /**
     * 添加日志
     * @param orderId 订单id
     * @param orderPeriodsId 订单分期支付id
     * @param periods 期数
     * @param recvShopId 卖家id
     * @param commodityBargainId  店铺报价表id
     * @param oldPayOrderLogId  重复支付原支付订单流水号
     * @param userId 用户id
     * @param userName 用户名称
     * @param payShopId 买家id
     * @param payType  支付类型：0余额，1网银，2票据
     * @param moneyStatus 金额状态：0未冻结，1冻结
     * @param businessType //金额类型：0订单金额，1佣金、2缴纳保证金、3年费、4采购申请平台砍价、5砍价手续费、6重复支付，7售后退款、8解冻保证金、9扣除保证金、10取消订单退款、11取消砍价服务费退款、12售后服务费退款、13签收解冻金额、14解冻砍价手续费、15缴纳物流保证金，16解冻物流保证金、17扣除物流保证金、18支付物流账单
     * @param orderType //支付类型：0支付，1退款、2冻结、3解冻
     * @param bankId
     * @param bankName
     * @param money
     * @return
     */
    public PayOrderLogDTO newLogDTO(Long orderId, Long orderPeriodsId, Integer periods, Long recvShopId,Long commodityBargainId, Long oldPayOrderLogId
            ,Long userId, String userName, Long payShopId, Integer payType, Integer moneyStatus, Integer businessType
            ,Integer orderType, String bankId, String bankName, BigDecimal money){

        return newLogDTO(orderId, orderPeriodsId, periods, recvShopId,commodityBargainId, oldPayOrderLogId
                ,userId, userName, payShopId, payType, moneyStatus, businessType
                ,orderType, bankId, bankName, money, null, null, null);
    }

    /**
     * 调用支付接口
     * @param saveBO
     * @param bo
     * @param payOrderVO
     */
    @Override
    public void saveHttpPay(PayOrderMotherSaveBO saveBO, PayOrderSaveBO bo, PayOrderVO payOrderVO) {
        saveHttpPay(saveBO, bo, payOrderVO, null);
    }

    /**
     * 调用支付接口
     * @param saveBO
     * @param bo
     * @param payOrderVO
     * @param orderType 订单类型：0普通，1询价
     */
    @Transactional(rollbackFor = ServiceException.class)
    public void saveHttpPay(PayOrderMotherSaveBO saveBO, PayOrderSaveBO bo, PayOrderVO payOrderVO, Integer orderType){
        if(bo.getPayType() == 0){//余额支付

            //修改payOrderLog 状态
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    try{
                        Result<List<PayOrderDTO>> result = payOrderService.saveBalancePay(saveBO);
                        if(result.success()){//成功
//                List<PayOrderDTO> payOrderDTOList = result.getData();
//                if(payOrderDTOList != null && payOrderDTOList.size() > 0){
//                    for(PayOrderDTO orderDTO : payOrderDTOList){
//                        savePaySuccessNotify(orderDTO);
//                    }
//                }
                            payOrderVO.setType(bo.getType());
                            payOrderVO.setOrderType(orderType);
                        } else {
                            throw new ServiceException(result.getCode(), result.getMsg());
                        }
                    } catch (ServiceException e) {
                        log.error("修改savePayOrderLogDTOStatus", e);
                    }
                }
            });


        } else {//网银支付
            Result<PayOrderMotherDTO> result = payOrderService.saveOnlineBankPay(saveBO);
            if(result.success()){//成功
                PayOrderMotherDTO motherDTO = result.getData();
                payOrderVO.setBankUrl(motherDTO.getBankUrl());
                payOrderVO.setType(bo.getType());
                payOrderVO.setOrderType(orderType);
            } else {
                throw new ServiceException(result.getCode(), result.getMsg());
            }
        }
    }

    @Override
    public void saveHttpPayBalance(PayOrderMotherSaveBO saveBO) {
        Result<List<PayOrderDTO>> result = payOrderService.saveBalancePay(saveBO);
        if(result.success()){//成功
//            List<PayOrderDTO> payOrderDTOList = result.getData();
//            if(payOrderDTOList != null && payOrderDTOList.size() > 0){
//                for(PayOrderDTO orderDTO : payOrderDTOList){
//                    savePaySuccessNotify(orderDTO);
//                }
//            }
        } else {
            throw new ServiceException(result.getCode(), result.getMsg());
        }
    }

    /**
     * 获取订单支付金额
     * @param ids
     * @param moneyVO
     * @param shopId
     */
    @Override
    public void getOrderInfo(String ids, PayOrderMoneyVO moneyVO, Long shopId) {
        BigDecimal money = BigDecimal.ZERO;
        List<PayOrderInfoVO> list = this.baseMapper.queryOrderCommodity(ids, shopId);
        if(list != null && list.size() > 0){
            Map<Long, PayOrderInfoVO> map = new HashMap<>();
            int periods = 1;
            int isCheckOrder = 0;
            int isPeriods1 = 0;//是否存在1期
            int billPayStatus = 0;//支付类型：0现金支付、1票据支付
            int orderPayType = 0;//是否有赊销订单：0无、1有
            int orderNums = 0;
            for(PayOrderInfoVO vo : list){

                if(map.get(vo.getId()) != null){
                    continue;
                }
                orderNums ++;
                if(vo.getPeriods() == 1){
                    isPeriods1 = 1;
                }
                if(vo.getPayType() == 1){
                    isCheckOrder = 1;
                }
                if(vo.getPurchaseFeeMoneyScalePrice().compareTo(BigDecimal.ZERO) > 0 ){
                    if(vo.getPurchaseFeeMoneyScalePriceStatus() != 2){
                        money = money.add(vo.getPurchaseFeeMoneyScalePrice());
                    }
                }
                money = money.add(vo.getRealPayMoney());

                //票据支付
                List<OrderPaymentTypeDTO> typeDTOList = orderPaymentTypeService.queryList(vo.getId());
                if(typeDTOList != null && typeDTOList.size() > 0){
                    for(OrderPaymentTypeDTO dto : typeDTOList){
                        if(dto.getPaymentType() == 2){
                            orderPayType = 1;
                        }
                        if(dto.getPaymentType() == 3){
                            billPayStatus = 1;
                        }
                    }

                }

                map.put(vo.getId(), vo);
            }

            if(isCheckOrder == 1){
                if(isPeriods1 == 0){
                    periods = 2;
                }
            }
            moneyVO.setPeriods(periods);
            moneyVO.setIsCheckOrder(isCheckOrder);
            moneyVO.setMoney(money);
            if(orderNums > 1){
                moneyVO.setBillPayStatus(0);
            } else {
                moneyVO.setBillPayStatus(billPayStatus);
            }
            moneyVO.setOrderPayType(orderPayType);
        }
    }

    /**
     * 获取订单支付金额
     * @param ids
     * @param shopId
     * @return
     */
    @Override
    public List<PayOrderInfoVO> queryOrderCommodity(String ids, Long shopId) {
        return this.baseMapper.queryOrderCommodity(ids, shopId);
    }

    /**
     * 获取申请平台砍价服务费
     * @param ids
     * @param moneyVO
     * @param shopId
     */
    @Override
    public void getPurchaseBargain(String ids, PayOrderMoneyVO moneyVO, Long shopId) {
        BigDecimal money = BigDecimal.ZERO;
        List<PayPurchaseOrderVO> list = this.baseMapper.queryPurchaseBargain(ids, shopId);
        if(list != null && list.size() > 0){
            for(PayPurchaseOrderVO vo : list){
                money = money.add(vo.getMoney());
            }

            moneyVO.setMoney(money);
        }
    }

    /**
     * 获取申请砍价服务费
     * @param ids
     * @param shopId
     * @return
     */
    @Override
    public List<PayPurchaseOrderVO> queryPurchaseBargain(String ids, Long shopId) {
        return this.baseMapper.queryPurchaseBargain(ids, shopId);
    }

    /**
     * 获取佣金待支付金额
     * @param ids
     * @param moneyVO
     * @param shopId
     */
    @Override
    public void getCommissionMoney(String ids, PayOrderMoneyVO moneyVO, Long shopId) {
        BigDecimal money = BigDecimal.ZERO;
        List<PayOrderInfoVO> list = this.baseMapper.queryCommissionMoney(ids, shopId);
        if(list != null && list.size() > 0){
            for(PayOrderInfoVO vo : list){
                money = money.add(vo.getLastCommissionMoney());
            }

            moneyVO.setMoney(money);
        }
    }

    @Override
    public List<PayOrderInfoVO> queryCommissionMoney(String ids, Long shopId) {
        return this.baseMapper.queryCommissionMoney(ids, shopId);
    }

    /**
     * 获取待缴砍价手续费金额
     * @param ids
     * @param moneyVO
     * @param shopId
     */
    @Override
    public void getPurchaseFeeMoneyScalePrice(String ids, PayOrderMoneyVO moneyVO, Long shopId) {
        BigDecimal money = BigDecimal.ZERO;
        List<PayOrderInfoVO> list = this.baseMapper.queryPurchaseFeeMoneyScalePrice(ids, shopId);
        if(list != null && list.size() > 0){
            for(PayOrderInfoVO vo : list){
                money = money.add(vo.getPurchaseFeeMoneyScalePrice());
            }

            moneyVO.setMoney(money);
        }
    }

    /**
     * 获取砍价成功后手续费
     * @param ids
     * @param shopId
     * @return
     */
    @Override
    public List<PayOrderInfoVO> queryPurchaseFeeMoneyScalePrice(String ids, Long shopId) {
        return this.baseMapper.queryPurchaseFeeMoneyScalePrice(ids, shopId);
    }

    /**
     * 获取待缴年费金额
     * @param ids
     * @param moneyVO
     */
    @Override
    public void getAnnualFee(String ids, PayOrderMoneyVO moneyVO) {
        BigDecimal money = BigDecimal.ZERO;
        List<PayShopVO> list = this.baseMapper.queryAnnualFee(ids);
        if(list != null && list.size() > 0){
            for(PayShopVO vo : list){
                money = money.add(vo.getMoney());
            }

            moneyVO.setMoney(money);
        }
    }

    /**
     * 获取待缴年费金额
     * @param ids
     * @return
     */
    @Override
    public List<PayShopVO> queryAnnualFee(String ids) {
        return this.baseMapper.queryAnnualFee(ids);
    }

    /**
     * 获取待缴保证金额
     * @param ids
     * @param moneyVO
     */
    @Override
    public void getMargin(String ids, PayOrderMoneyVO moneyVO) {
        BigDecimal money = BigDecimal.ZERO;
        List<PayShopVO> list = this.baseMapper.queryMargin(ids);
        if(list != null && list.size() > 0){
            for(PayShopVO vo : list){
                money = money.add(vo.getMoney());
            }

            moneyVO.setMoney(money);
        }
    }

    /**
     * 获取待缴保证金额
     * @param ids
     * @return
     */
    @Override
    public List<PayShopVO> queryMargin(String ids) {
        return this.baseMapper.queryMargin(ids);
    }

    /**
     * 扣除保证金总和
     * @param shopId
     * @param type
     * @return
     */
    @Override
    public BigDecimal querySumDeductMarginMoney(Long shopId, int type) {
        return baseMapper.querySumDeductMarginMoney(shopId, type);
    }

    /**
     * 查看保证金使用记录和退还保证金记录
     * @param bo
     * @return
     */
    @Override
    public Page<PayOrderLogVO> queryPagePayOrderLog(PayOrderLogBO bo) {
        Page<PayOrderLogVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<PayOrderLogVO> vos = baseMapper.queryPagePayOrderLog(page, bo);
        page.setRecords(vos);
        return page;
    }

    /**
     * 获取物流待支付的保证金
     * @param shopId
     * @param moneyVO
     */
    @Override
    public void getLogisticsMargin(Long shopId, PayOrderMoneyVO moneyVO) {
        BigDecimal money = this.baseMapper.getLogisticsMargin(shopId);
        if(money == null || money.compareTo(BigDecimal.ZERO) <= 0){
            money = BigDecimal.ZERO;
        }

        moneyVO.setMoney(money);
    }

    /**
     * 获取物流待支付的保证金
     * @param shopId
     * @return
     */
    @Override
    public List<PayShopVO> queryLogisticsMargin(Long shopId) {
        BigDecimal money = this.baseMapper.getLogisticsMargin(shopId);
        if(money == null || money.compareTo(BigDecimal.ZERO) <= 0){
            return null;
        }
        PayShopVO payShopVO = new PayShopVO();
        payShopVO.setId(shopId);
        payShopVO.setMoney(money);
        List<PayShopVO> list = new ArrayList<>();
        list.add(payShopVO);
        return list;
    }

    /**
     * 获取物流账单金额
     * @param ids
     * @param moneyVO
     */
    @Override
    public void getLogisticsBill(String ids, Long shopId, PayOrderMoneyVO moneyVO) {
        List<PayShopVO> list = this.baseMapper.queryLogisticsBill(ids, shopId);
        if(list == null || list.size() == 0){
            moneyVO.setMoney(BigDecimal.ZERO);
        } else {
            BigDecimal totalMoney = BigDecimal.ZERO;
            for(PayShopVO vo : list){
                totalMoney =  totalMoney.add(vo.getMoney());
            }

            moneyVO.setMoney(totalMoney);
        }
    }

    /**
     * 获取物流账单金额
     * @param ids
     * @return
     */
    @Override
    public List<PayShopVO> queryLogisticsBill(String ids, Long shopId) {
        return this.baseMapper.queryLogisticsBill(ids, shopId);
    }




    /**
     * 修改日志状态
     * @param id
     * @param payOrderId
     * @param status
     * @param moneyStatus
     */
    @Override
    public void savePayOrderLogDTOStatus(Long id, Long payOrderId, int status, Integer moneyStatus){
        if(status > 0){
            PayOrderLogDTO logDTO = new PayOrderLogDTO();
            logDTO.setId(id);
            logDTO.setStatus(status);
            logDTO.setPayOrderId(payOrderId == null ? null : payOrderId.toString());
            logDTO.setMoneyStatus(moneyStatus);
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("id", id);
            wrapper.ne("status", 2);
            if(!this.update(logDTO, wrapper)){
                throw new ServiceException(CodeEnum.FAIL_100011);
            }
        }
    }

    /**
     * 网银充值
     * @param payOrderVO
     * @param shopId
     * @param money
     * @param bankId
     * @param businessId
     * @param usage
     * @param pageNotificationUrl
     */
    public void saveRechargeByOnlineBank(PayOrderVO payOrderVO, Long shopId, BigDecimal money, String bankId, Long businessId, String usage, String pageNotificationUrl){
        PayUserRechargeSaveBO saveBO = new PayUserRechargeSaveBO();
        saveBO.setUserId(shopId);
        saveBO.setMoney(money);
        saveBO.setBankId(bankId);
        saveBO.setBusinessId(businessId);
        saveBO.setUsage(usage);
        saveBO.setNotificationurl(pageNotificationUrl);
        Result<PayUserRechargeDTO> result = payUserRechargeService.saveRechargeByOnlineBank(saveBO);
        if(result.success()){
            payOrderVO.setBankUrl(result.getData().getZjPayUrl());
        } else {
            throw new ServiceException(result.getCode(), result.getMsg());
        }
    }

    /**
     * 解冻金额
     * @param shopId
     * @param businessId 业务流水号
     * @param money
     * @param usage
     */
    public void saveUnfreezeMoney(Long shopId, Long businessId, BigDecimal money, String usage){
        List<PayUserMoneySaveBO> paySaveBOlist = new ArrayList<>();
        PayUserMoneySaveBO payUserMoneySaveBO = new PayUserMoneySaveBO();
        payUserMoneySaveBO.setUserId(shopId);
        payUserMoneySaveBO.setMoney(money);
        payUserMoneySaveBO.setUsage(usage);
        payUserMoneySaveBO.setBusinessId(businessId);
        paySaveBOlist.add(payUserMoneySaveBO);
        Result result = payUserRechargeService.saveUnfreezeMoney(paySaveBOlist);
        if(!result.success()){
            throw new ServiceException(result.getCode(), result.getMsg());
        }
    }

    /**
     * 支付成功回调
     * @param orderDTO
     */
    @Override
    @Transactional
    public void savePaySuccessNotify(PayOrderDTO orderDTO) {
        log.error("-------------支付回调--------savePaySuccess-----------"+ JSON.toJSONString(orderDTO));
        PayOrderLogDTO logDTO = this.selectById(orderDTO.getBusinessOrderWaterNo());
        if(logDTO == null){
            log.error("支付回调错误savePaySuccess.PayOrderLogDTO is null--->>>"  + JSON.toJSONString(orderDTO));
            throw new ServiceException(CodeEnum.FAIL_100002);
        }
        if(logDTO.getStatus() == 2 || logDTO.getStatus() == 3){
            log.error("支付回调错误savePaySuccess.PayOrderLogDTO is do  已处理过了--->>>"  + JSON.toJSONString(orderDTO));
            throw new ServiceException(CodeEnum.FAIL_100002);
        }

        //修改payOrderLog 状态
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void beforeCommit(boolean readOnly) {
            try{
                savePayOrderLogDTOStatus(logDTO.getId(), orderDTO.getId(), orderDTO.getStatus(), null);
            } catch (ServiceException e) {
                log.error("修改savePayOrderLogDTOStatus", e);
            }
            }
        });
        if(orderDTO.getStatus() != 2) {//支付成功
            log.error("支付失败回调 savePaySuccess--->>>"  + JSON.toJSONString(orderDTO));
            return;
        }
        //金额类型：0订单金额，1佣金、2缴纳保证金、3年费、4采购申请平台砍价、5砍价手续费、6重复支付，7售后退款、8解冻保证金、9扣除保证金、10取消订单退款、11取消砍价服务费退款、12售后服务费退款、13签收解冻金额、14解冻砍价手续费、15缴纳物流保证金，16解冻物流保证金、17扣除物流保证金、18支付物流账单
        if(orderDTO.getBusinessType() == 0){
            payNotifyService.saveOrder(orderDTO, logDTO);
        } else if(orderDTO.getBusinessType() == 1){//1佣金
            payNotifyService.saveOrderCommissionMoney(orderDTO, logDTO);
        } else if(orderDTO.getBusinessType() == 2){//2店铺保证金
        } else if(orderDTO.getBusinessType() == 3){//3年费
            payNotifyService.saveAnnualFee(orderDTO, logDTO);
        } else if(orderDTO.getBusinessType() == 4){//4采购申请平台砍价
            payNotifyService.saveOrderPurchaseFeeMoney(orderDTO, logDTO);
        } else if(orderDTO.getBusinessType() == 5){//5砍价手续费
            payNotifyService.saveOrderPurchaseFeeMoneyScalePrice(orderDTO, logDTO);
        } else if(orderDTO.getBusinessType() == 6){//6重复支付
        } else if(orderDTO.getBusinessType() == 7){//7售后退款退款
            payNotifyService.saveOrderRefundMoney(orderDTO, logDTO);
        } else if(orderDTO.getBusinessType() == 9){//7扣除保证金
            payNotifyService.saveDeductMargin(orderDTO, logDTO);
        } else if(orderDTO.getBusinessType() == 10){//取消退款
            payNotifyService.saveOrderCancelRefundMoney(orderDTO, logDTO);
        } else if(orderDTO.getBusinessType() == 11){//取消退砍价手续费
            payNotifyService.saveOrderCancelPurchaseFeeMoneyScalePrice(orderDTO, logDTO);
        } else if(orderDTO.getBusinessType() == 12){//售后订单砍价服务费
            payNotifyService.saveOrderRefundPurchaseFeeMoneyScalePrice(orderDTO, logDTO);
        } else if(orderDTO.getBusinessType() == 17){//17扣除物流保证金
            payNotifyService.saveLogisticsDeductMargin(orderDTO, logDTO);
        } else if(orderDTO.getBusinessType() == 18){//18支付物流账单
            payNotifyService.saveLogisticsBill(orderDTO, logDTO);
        } else if(orderDTO.getBusinessType() == 19){//19退款佣金
            payNotifyService.saveOrderRefundCommissionMoney(orderDTO, logDTO);
        }
    }

    /**
     * 充值成功回调
     * @param rechargeDTO
     */
    @Override
    public void saveRechargeSuccessNotify(PayUserRechargeDTO rechargeDTO) {
        PayOrderLogDTO logDTO = this.selectById(rechargeDTO.getBusinessId());
        if(logDTO == null){
            return;
        }

        this.savePayOrderLogDTOStatus(logDTO.getId(), null, rechargeDTO.getStatus(), 0);
        if(rechargeDTO.getStatus() != 2) {
            return;
        }
        payNotifyService.saveRechargeSuccess(logDTO);
    }


}
